#include <iostream>
#include<unistd.h>
#include<assert.h>
#include<string>
#include<cstdio>
#include<cstring>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;
int main()
{
    //1.创建管道
    int pipefd[2]={0};
    int n = pipe(pipefd);
    assert(n!=-1);
    (void)n;
#ifdef DEBUGE
    cout<<"pipefd[0]:"<<pipefd[0]<<endl;
    cout<<"pipefd[1]:"<<pipefd[1]<<endl;
#endif
    //2.创建子进程
    pid_t id =fork();
    assert(id!=-1);
    //3.构建单向通信，父进程写入，子进程读取
    if(id==0)
    {
        //子进程--读取
        //关闭写入端
        close(pipefd[1]);
        char buffer[1024*8];
        int count2=0;
        while(1)
        {
            sleep(1);
            //写入的一方，fd没有关闭，如果管道有数据就读，没有就等
            //写入的一方，fd关闭，读取的一方read会返回0，表示读到文件结尾
            ssize_t s= read(pipefd[0],buffer,sizeof(buffer)-1);
            count2++;
            if(count2==5) 
            {
                cout<<"读端关闭"<<endl;
                break;
            }
            if(s>0)//读取成功
            {
                buffer[s]=0;
                cout<<"child get a message["<<getpid()<<"]"<<"Father#"<<buffer<<endl;
            } 
            else if(s==0)
            {
                cout<<"writer quit(child)"<<endl;
                break;
            }
            
        }
        close(pipefd[0]);
        exit(0);
    }
    //父进程--写入
    //关闭读取端
    close(pipefd[0]);
    string message="我是父进程，我正在给子进程发消息";
    int count=0;
    char send_buffer[1024];
    while(true)
    {
        snprintf(send_buffer,sizeof(send_buffer),"%s[%d]:%d",message.c_str(),getpid(),count++);
        ssize_t m=write(pipefd[1],send_buffer,strlen(send_buffer));
        sleep(1);
        cout<<count<<endl;
        if(count==10)
        {
            cout<<"writer quit(father)"<<endl;
            break;

        }
    }
    close(pipefd[1]);
    pid_t ret=waitpid(id,nullptr,0);
    assert(ret>0);
    (void)ret;
    return 0;
}